<!DOCTYPE html>
<body lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <style type="text/css">
        body,
        html,
        #allmap {
            width: 90%;
            height: 100%;
            overflow: hidden;
            margin-left: 50px;
            font-family: "微软雅黑";
        }
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=V6RjjChFXrifV2z41z0sYQEO"></script>
    <th:block th:include="include :: header('地图详情及经纬度上传')"/>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>高速：</label>
                            <select id="highSpeedRoad" class="form-control"
                                    th:with="type=${@rdHighSpeedRoadController.findAll()}">
                                <option value="" selected="selected">--请选择高速--</option>
                                <option th:each="dict : ${type}" th:text="${dict.name}"
                                        th:value="${dict.id}"></option>
                            </select>
                        </li>
                        <li>
                            <label>路段：</label>
                            <select id="roadSection" class="form-control">
                                <option value="" selected="selected">--请选择路段--</option>
                            </select>
                        </li>
                        <li>
                            <label>上下行：</label>
                            <select class="selectpicker form-control" data-live-search="true" id="roadDirection">
                                <option value="1">下行</option>
                                <option value="0" selected>上行</option>
                            </select>
                        </li>
                    </ul>
                </div>
            </form>
        </div>
        <div class="btn-group-sm" id="toolbar" role="group">
            <button class="btn btn-primary" disabled=true id="uploadButton"
                    onclick="$.operate.edit(sectionId)"
                    shiro:hasPermission="road:road_map:edit">
                <i class="fa fa-plus"></i> 上传
            </button>
        </div>
        <div id="allmap"></div>
    </div>
</div>

<th:block th:include="include :: footer"/>
<!--地图处理-->
<script th:inline="javascript">
    var sectionId;
    //上下行分隔符 ，点分隔符 ，经纬度分隔符
    var upDownDivision = "|", loAndLaDivision = ",";
    $("#roadSection,#roadDirection").change(function () {
        var sectionElement = $('#roadSection').val();
        if (sectionElement != "--请选择路段--"){
            sectionId = jsonArr[$('#roadSection').val()].id;
            //获取上行或下行的选择,上行为0，下行为1
            var upOrDownFlag = $('#roadDirection').val();
            var longAndLatitudes = jsonArr[sectionElement].remark;
            $("#uploadButton").attr("disabled",false);
            //将上下行经纬度信息截取成字符数组
            var upAndDownPoints = longAndLatitudes.split(upDownDivision);

            var arrayList = [];

            if (upAndDownPoints[upOrDownFlag]) {
                var longAndLatitude = upAndDownPoints[upOrDownFlag].split(loAndLaDivision);
                //纬度
                var centerLatitude;
                //经度
                var centerLongtitude;
                var mapScale = 10;
                var lastPoint;
                for (var i = 0; i < longAndLatitude.length;) {
                    var latitude = parseFloat(longAndLatitude[i++]);
                    var longtitude = parseFloat(longAndLatitude[i++]);
                    var sectionPoint = new BMap.Point(latitude, longtitude);
                    if (i == 2) {
                        centerLatitude = latitude;
                        centerLongtitude = longtitude;
                    }
                    if (i == 4) {
                        centerLatitude = (centerLatitude + latitude) / 2;
                        centerLongtitude = (centerLongtitude + longtitude) / 2;
                        lastPoint = sectionPoint;
                        continue;
                    }
                    arrayList.push(sectionPoint);
                }
                arrayList.push(lastPoint);
                // 设置地图中心点
                var map = new BMap.Map("allmap");
                map.centerAndZoom(new BMap.Point(centerLatitude, centerLongtitude), mapScale);
                map.enableScrollWheelZoom(true);
                showPoly(arrayList, map);
            } else {
                $.modal.alert("该方向暂无数据！");
            }
        } else {
            $("#uploadButton").attr("disabled",true);
            $.modal.alert("该路段无经纬度信息或未选择路段！");
        }

    })


    function showPoly(pointList, map) {

        //循环显示点对象
        for (c = 0; c < pointList.length; c++) {
            var marker = new BMap.Marker(pointList[c]);
            map.addOverlay(marker);
            var labelName = "途径点";
            //将途经点按顺序添加到地图上
            if (c == 0) {
                labelName = "起点";
            } else if (c == pointList.length - 1) {
                labelName = "终点";
            }
            var label = new BMap.Label(labelName, {
                offset: new BMap.Size(20, -10)
            });
            label.setStyle({
                color:"red",
                fontSize : "16px",
                backgroundColor :"0.05",
                border:"0"
            });

            marker.setLabel(label);
        }

        var group = Math.floor(pointList.length / 11);
        var mode = pointList.length % 11;

        var driving = new BMap.DrivingRoute(map, {
            onSearchComplete: function (results) {
                if (driving.getStatus() == BMAP_STATUS_SUCCESS) {
                    var plan = driving.getResults().getPlan(0);
                    var num = plan.getNumRoutes();
                    for (var j = 0; j < num; j++) {
                        var pts = plan.getRoute(j).getPath(); //通过驾车实例，获得一系列点的数组
                        var polyline = new BMap.Polyline(pts);
                        console.log(pts)
                        map.addOverlay(polyline);
                    }
                }
                console.log(results.getPlan(0).getDistance(true));
            }
        });
        for (var i = 0; i < group; i++) {
            var waypoints = pointList.slice(i * 11 + 1, (i + 1) * 11);
            //注意这里的终点如果是11的倍数的时候，数组可是取不到最后一位的，所以要注意终点-1喔。感谢song141的提醒，怪我太粗心大意了~
            driving.search(pointList[i * 11], pointList[(i + 1) * 11 - 1], {
                waypoints: waypoints
            }); //waypoints表示途经点
        }
        if (mode != 0) {
            var waypoints = pointList.slice(group * 11, pointList.length - 1); //多出的一段单独进行search
            driving.search(pointList[group * 11], pointList[pointList.length - 1], {
                waypoints: waypoints
            });
        }
    }
</script>
<!--经纬度增删改、导出-->
<script th:inline="javascript">
    var mapPrefix = ctx + "road/road_map";

    $(function () {
        var options = {
            updateUrl: mapPrefix + "/upload/{id}",
        };
        $.table.init(options);
    });

</script>
<!--级联下拉框处理-->
<script th:inline="javascript">
    var prefix = ctx + "road/road_section";
    //json对象数组，用来存放section对象
    var jsonArr = [];
    <!--页面加载时运行此函数  放在最前端 -->
    $(document).ready(function () {

        <!-- 对下拉选择列表进行监听-->
        $("#highSpeedRoad").change(function () {
            var hspId = $('#highSpeedRoad').val();

            var data = {
                rdHighSpeedRoad: {
                    id: hspId
                }
            };
            <!--异步请求-->
            $.ajax({
                <!--请求路径，与后端对应-->
                url: prefix + "/findRoadSectionList",
                <!--请求类型-->
                type: "post",
                <!--期待的返回数据类型-->
                dataType: "json",
                <!--传递给后端的数据  "regionId"是传递给后端的参数名   t是本页面的参数-->
                data: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                <!--前端接收数据成功时执行的该函数-->
                success: function (data) {
                    <!--清空下拉框中的缓存-->
                    $("#roadSection").empty();
                    jsonArr = data;
                    <!--避免下拉框的值不变-->
                    $("#roadSection").append("<option>--请选择路段--</option>");

                    <!--使用循环解析后端传来的数据，并用使用js动态拼接html语言-->
                    for (var i = 0; i < data.length; i++)
                        $("#roadSection").append("<option value='" + i + "'>" + data[i].sectionName + "</option>");
                }
            });
        });
    });
</script>
</body>
</html>